package com.leetcode.partition18;

import java.io.*;
import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2022/2/24 15:01
 */
public class LC1706球会落何处 {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        int[][] grid = new int[n][m];
        for (int i = 0; i < n; i++) {
            ss = reader.readLine().split(" ");
            for (int j = 0; j < m; j++) grid[i][j] = Integer.parseInt(ss[j]);
        }
        writer.write(Arrays.toString(findBall(grid)));
        writer.flush();
    }

    public static int[] findBall(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        int[] answer = new int[m];
        for (int i = 0; i < m; i++) {
            int r = 0, c = i;
            boolean flag = true;
            while (r < n) {
                //这个球应该滚到的列
                int next = c + grid[r][c];
                //如果球滚到了边缘或者当前位置的隔板方向与下一个位置的隔板方向不一致，就会被卡死
                if (next < 0 || next >= m || grid[r][c] != grid[r][next]) {
                    flag = false;
                    break;
                }
                r++;
                c = next;
            }
            answer[i] = flag ? c : -1;
        }
        return answer;
    }
}
